package com.movie.service;

import com.movie.dto.CategoryDTO;
import com.movie.entity.Category;
import com.movie.repository.CategoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryService {
    
    private final CategoryRepository categoryRepository;
    
    public List<CategoryDTO> findAll() {
        List<Category> categories = categoryRepository.findAll();
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    public List<CategoryDTO> findByType(String type) {
        List<Category> categories = categoryRepository.findByType(type);
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    public CategoryDTO findById(Long id) {
        Category category = categoryRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        return convertToDTO(category);
    }
    
    @Transactional
    public CategoryDTO create(CategoryDTO categoryDTO) {
        // 检查名称是否已存在
        if (categoryRepository.existsByName(categoryDTO.getName())) {
            throw new RuntimeException("分类名称已存在");
        }
        
        // 检查标识是否已存在
        if (categoryRepository.existsBySlug(categoryDTO.getSlug())) {
            throw new RuntimeException("分类标识已存在");
        }
        
        Category category = convertToEntity(categoryDTO);
        category.setItemCount(0);
        Category saved = categoryRepository.save(category);
        return convertToDTO(saved);
    }
    
    @Transactional
    public CategoryDTO update(Long id, CategoryDTO categoryDTO) {
        Category existing = categoryRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        // 检查名称是否被其他分类使用
        if (!existing.getName().equals(categoryDTO.getName()) && 
            categoryRepository.existsByName(categoryDTO.getName())) {
            throw new RuntimeException("分类名称已存在");
        }
        
        // 检查标识是否被其他分类使用
        if (!existing.getSlug().equals(categoryDTO.getSlug()) && 
            categoryRepository.existsBySlug(categoryDTO.getSlug())) {
            throw new RuntimeException("分类标识已存在");
        }
        
        BeanUtils.copyProperties(categoryDTO, existing, "id", "itemCount", "createdAt", "updatedAt");
        Category updated = categoryRepository.save(existing);
        return convertToDTO(updated);
    }
    
    @Transactional
    public void delete(Long id) {
        Category category = categoryRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        
        // 检查分类下是否有影片
        Integer movieCount = categoryRepository.countMoviesByCategoryId(id);
        if (movieCount > 0) {
            throw new RuntimeException("该分类下还有影片，无法删除");
        }
        
        categoryRepository.delete(category);
    }
    
    public List<CategoryDTO> findActiveCategories() {
        List<Category> categories = categoryRepository.findByStatusTrue();
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    public List<CategoryDTO> findActiveCategoriesByType(String type) {
        List<Category> categories = categoryRepository.findByStatusTrueAndType(type);
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    

    
    public Category findByName(String name) {
        return categoryRepository.findByName(name)
                .orElse(null);
    }

    public List<CategoryDTO> searchCategories(String keyword, String type) {
        List<Category> categories;
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 如果有搜索关键词，进行模糊搜索
            if (type != null && !type.trim().isEmpty()) {
                categories = categoryRepository.findByNameContainingIgnoreCaseAndType(keyword, type);
            } else {
                categories = categoryRepository.findByNameContainingIgnoreCase(keyword);
            }
        } else {
            // 如果没有搜索关键词，根据类型筛选
            if (type != null && !type.trim().isEmpty()) {
                categories = categoryRepository.findByType(type);
            } else {
                categories = categoryRepository.findAll();
            }
        }
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    private CategoryDTO convertToDTO(Category category) {
        CategoryDTO dto = new CategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }
    
    private Category convertToEntity(CategoryDTO dto) {
        Category category = new Category();
        BeanUtils.copyProperties(dto, category);
        return category;
    }
}